import { forwardRef, Inject, Injectable, OnModuleInit } from "@nestjs/common";
import { EtcdService } from "@app/etcd";
import { Observable } from "rxjs";
import { ConnectStateService } from "./share/connect-state/connect-state.service";

@Injectable()
export class GatewayService implements OnModuleInit {
  constructor(
    @Inject(EtcdService) private readonly etcdService: EtcdService,
    private readonly connectStateService: ConnectStateService,
  ) {}

  async onModuleInit(): Promise<any> {
    const serviceInstance = await this.etcdService.discoverService();
    console.log(`当前所有在线的服务为:${JSON.stringify(serviceInstance)}`);
    this.initOnlineService(serviceInstance);
    const ans: Observable<any> = await this.etcdService.watchService();
    ans.subscribe({
      next: (value) => {
        const { systemName, status } = value;
        this.connectStateService.changeState(systemName, status);
      },
    });
  }

  initOnlineService(serviceInstance) {
    for (const [k, v] of Object.entries(serviceInstance)) {
      const systemName = k.split("-")[1];
      this.connectStateService.changeState(systemName, true);
    }
  }
}
